﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VotesResults.Daos;
using VotesResults.Daos.EntityFramework;
using VotesResults.Models;

namespace VotesResults.Controllers
{
    public class VoteController : Controller
    {
        private readonly IQuestionDao _questionDao = new QuestionDao();
        private readonly IVoteDao _voteDao = new VoteDao();
        //
        // GET: /Vote/

        public ActionResult Index(int voteId, int groupId)
        {
            List<QuestionModel> questionModels = new List<QuestionModel>();
            foreach (Question question in _questionDao.Load(voteId))
            {
                questionModels.Add(
                    new QuestionModel
                        {
                            Id = question.Id, 
                            Content = question.Content,
                            Mark = 0
                        });
            }

            return View(
                new VoteIndexModel
                    {
                        VoteId = voteId,
                        VoteName = _voteDao.Get(voteId).Name,
                        GroupId = groupId,
                        QuestionModels = questionModels
                    });
        }

        [HttpPost]
        public ActionResult Index(int voteId, int groupId, VoteIndexModel voteIndexModel)
        {
            using (VotesResultsEntities db = new VotesResultsEntities())
            {
                if (voteIndexModel.QuestionModels != null)
                    foreach (QuestionModel questionModel in voteIndexModel.QuestionModels)
                    {
                        RelVoteQuestionGroupSession relVoteQuestionGroupSession = 
                            new RelVoteQuestionGroupSession
                                {
                                    VoteId = voteIndexModel.VoteId, 
                                    GroupId = voteIndexModel.GroupId, 
                                    QuestionId = questionModel.Id, 
                                    Session = DateTime.Now, 
                                    Mark = questionModel.Mark 
                                };
                        db.AddToRelVoteQuestionGroupSession(relVoteQuestionGroupSession);
                        db.SaveChanges();
                    }
            }
            return RedirectToAction("Result", new { voteId });
        }

        public ActionResult Result(int voteId)
        {
            return View(_voteDao.Get(voteId));
        }
    }
}
